package com.thenie.chat.interceptor;

import com.thenie.chat.pojo.User;
import com.thenie.chat.service.IUserService;
import com.thenie.chat.util.CookieUtil;
import com.thenie.chat.util.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 未登陆 拦截器
 * @Author thenie
 * @Data 2022/5/19 14:04
 */
@Component
@Slf4j
public class NotLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        //已经登陆，可以放行
        if (!StringUtils.isEmpty(userTicket)){
            User user = userService.getUserByCookie(userTicket, request, response);

            if (user!=null){
                request.setAttribute("currentUser",user);
                return true;
            }
        }

        //未登录，跳转登陆页面
        log.warn("未登录，跳转到登陆页面,ip:{}", IPUtil.getIpAddress(request));
        response.sendRedirect("/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
